package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author shh
 * @Date 2025-10-10
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties properties;
    @Autowired
    private UserMapper userMapper;

    /**
     * 微信用户登录
     * @param dto
     * @return
     */
    @Override
    public User login(UserLoginDTO dto) {
        //1.同HttpClient请求构造登录凭证校验请求
        //2.构造请求参数
        String url = "https://api.weixin.qq.com/sns/jscode2session";//登录凭证校验接口
        Map<String,String> paramMap = new HashMap<>();//登录凭证校验接口的请求参数
        paramMap.put("appid",properties.getAppid());//登录凭证校验接口的请求参数：appid
        paramMap.put("secret",properties.getSecret());//登录凭证校验接口的请求参数：secret
        paramMap.put("js_code",dto.getCode());//登录凭证校验接口的请求参数：js_code
        paramMap.put("grant_type","authorization_code");//登录凭证校验接口的请求参数：grant_type
        //3.调用HttpClient请求登录凭证校验接口
        String res = HttpClientUtil.doGet(url,paramMap);//登录凭证校验接口的响应结果
        log.info("登录凭证校验响应结果：{}",res);
        //2.解析登录凭证校验响应结果，获取openid
        JSONObject parse = JSONObject.parseObject(res);//登录凭证校验接口的响应结果解析为JSONObject对象
        String openid = parse.getString("openid");//登录凭证校验接口的响应结果中的openid字段
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //3.判断是否是新用户根据openid查询数据库
        User user = userMapper.selectByOpenid(openid);//根据openid查询用户是否存在
        //4.如果是新用户，插入数据库
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(java.time.LocalDateTime.now())
                    .name(openid.substring(0,4))
                    .build();
            userMapper.insert(user);
        }
        //5.如果不是新用户，返回用户信息

        return user;
    }
}
